package com.dmall.graph.floodfill;

public class Leetcode130 {

    private int R, C;
    private char[][] grid;
    private boolean[][] visited;

    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public void solve(char[][] board) {
        R = board.length;
        if (R == 0) {
            return;
        }
        C = board[0].length;
        if (C == 0) {
            return;
        }
        this.grid = board;
        visited = new boolean[R][C];
        for (int i = 0; i < R; i++) {
            dfs(i, 0);
            dfs(i, C - 1);
        }

        for (int i = 0; i < C; i++) {
            dfs(0, i);
            dfs(R - 1, i);
        }

        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (!visited[i][j]) {
                    grid[i][j] = 'X';
                }
            }
        }
    }

    private void dfs(int x, int y) {
        if (grid[x][y] == 'O') {
            visited[x][y] = true;
            for (int i = 0; i < dirs.length; i++) {
                int nextx = x + dirs[i][0];
                int nexty = y + dirs[i][1];
                if (inArea(nextx, nexty) && !visited[nextx][nexty] && grid[nextx][nexty] == 'O') {
                    dfs(nextx, nexty);
                }
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        char[][] board = {
                {'X', 'X', 'X', 'X'},
                {'X', 'O', 'O', 'X'},
                {'X', 'X', 'O', 'X'},
                {'X', 'O', 'X', 'X'}
        };
        Leetcode130 leetcode130 = new Leetcode130();
        leetcode130.solve(board);
        for (char[] chars : board) {
            for (char c : chars) {
                System.out.print(c + " ");
            }
            System.out.println();
        }
    }
}
